/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bice.controller.service;

import com.bice.controller.dao.Dao;
import com.bice.controller.entity.BiceUser;
import com.bice.controller.entity.Post;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;

/**
 *
 * @author Sirius
 */
@Service
public class PostService {
    
    @Resource
    private Dao<Post, Serializable> dao;

    /**
     * Constructor of user service
     */
    public PostService() {
    }
    
    public void post(BiceUser from, BiceUser to, String message) {
        post(from, to, message, null);
    }
    
    public void post(BiceUser from, BiceUser to, String message, Post parent) {
        Post post = new Post();
        post.setParent(parent);
        post.setFrom(from);
        post.setTo(to);
        post.setMessage(message);
        post.setPostAt(new Date());
        post.setCode(from.getCode() + "-" + post.getPostAt().getTime());
        dao.save(post);
        parent.setPostAt(post.getPostAt());
        dao.update(parent);
    }
    
    public List<Post> getMessagesTo(BiceUser to) {
        DetachedCriteria criteria = DetachedCriteria.forClass(Post.class);
        criteria.add(Restrictions.eq("to", to));
        criteria.add(Restrictions.isNull("parent"));
        criteria.addOrder(Order.desc("postAt"));
        return dao.get(criteria);
    }
    
    public List<Post> getMessagesTo(Post post) {
        DetachedCriteria criteria = DetachedCriteria.forClass(Post.class);
        criteria.add(Restrictions.eq("parent", post));
        criteria.addOrder(Order.asc("postAt"));
        return dao.get(criteria);
    }
    
}